import eel
import json
from myUtils.stock import StockUtil
import re
import pandas as pd
import math
import numpy as np

print("开始初始化！")
eel.init('web')


# step页面初始化
# 1. 获取所有策略内容（用于选择的enum和所有strategy）
# 2. 获取股票列表用于选择 （只有stock.json 里面的所有股票列表信息，不返回具体股票detail内容）
# stock stockEnum strategyEnum allStrategy parameterEnum logicSymbolEnum
@eel.expose
def step_init():
    return_json = {}
    strategy_json = {}
    with open('./json/strategy.json', 'r', encoding='utf8')as fp:
        strategy_json = json.load(fp)
    return_json["strategyEnum"] = strategy_json["allStrategyEnum"]
    return_json["allBuyLogicEnum"] = strategy_json["allBuyLogicEnum"]
    return_json["allSellLogicEnum"] = strategy_json["allSellLogicEnum"]
    return_json["parameterEnum"] = strategy_json["parameterEnum"]
    return_json["logicSymbolEnum"] = strategy_json["logicSymbolEnum"]
    all_buy_logic = strategy_json["allBuyLogic"]
    all_sell_logic = strategy_json["allSellLogic"]
    return_json["allStrategy"] = {}
    return_all_strategy = {}
    all_strategy = strategy_json["allStrategy"]
    for strategy_name_item in strategy_json["allStrategyEnum"]:
        return_strategy_item_json = {}
        strategy_item = all_strategy[strategy_name_item]
        return_strategy_item_json["name"] = strategy_item["name"]

        return_strategy_buy_logic = {}
        return_strategy_item_json["logicBuyEnum"] = strategy_item["logicBuy"]
        for buy_logic_name_item in strategy_item["logicBuy"]:
            return_strategy_buy_logic[buy_logic_name_item] = all_buy_logic[buy_logic_name_item]
        return_strategy_item_json["logicBuy"] = return_strategy_buy_logic

        return_strategy_sell_logic = {}
        return_strategy_item_json["logicSellEnum"] = strategy_item["logicSell"]
        for sell_logic_name_item in strategy_item["logicSell"]:
            return_strategy_sell_logic[sell_logic_name_item] = all_sell_logic[sell_logic_name_item]
        return_strategy_item_json["logicSell"] = return_strategy_sell_logic

        return_all_strategy[strategy_name_item] = return_strategy_item_json

    return_json["allStrategy"] = return_all_strategy

    stock_json = {}
    with open('./json/stock.json', 'r')as fp:
        stock_json = json.load(fp)
    return_json["stock"] = stock_json["stock"]
    return_json["stockEnum"] = stock_json["stockEnum"]

    # print(return_json)

    return return_json


@eel.expose
def get_stock_info(code):
    print("get_stock_info-开始")
    return_data = StockUtil.get_stock_by_code(code)
    # print(return_data)
    return_json = {}
    return_json["data"] = str(return_data)
    # print(return_json)
    return return_json


# 股票code 根据策略判断
@eel.expose
def run_strategy(code, strategy_name):
    strategy_file = open('json/strategy.json', 'r')
    strategy_file_json = json.load(strategy_file)
    strategy_json = {}
    target_strategy_info = strategy_file_json["allStrategy"][strategy_name]
    strategy_json["name"] = target_strategy_info["name"]
    logic_buy = []
    for logicNameItem in target_strategy_info["logicBuy"]:
        logic_buy.append(strategy_file_json["allBuyLogic"][logicNameItem])
    logic_sell = []
    for logicNameItem in target_strategy_info["logicSell"]:
        logic_sell.append(strategy_file_json["allSellLogic"][logicNameItem])
    strategy_json["buyLogic"] = logic_buy
    strategy_json["sellLogic"] = logic_sell
    # strategy.json 内容改成详细策略
    # print(strategy_json)


# ---------------------------------------
# judge
# ----------------------------------------

code_num = -1

strategy = {}
# 指向下一个index （完成逻辑后+1）
now = 0
# 当前状态是否为买 true:可买
status_buy = True
# 自身资产
asset_own = 10000
# 股市资产
asset_share = 0
asset_all = 10000
# 持股数
stock_num = 0
data_all = []
data_open = []
data_close = []
data_highest = []
data_lowest = []
data_MA5 = []
data_MA10 = []
data_MA20 = []
data_MA30 = []
data_increase = []
data_time = []

data_trend = []
data_max_after_buy = []

buy_arr = []
sell_arr = []
mark_point_arr = []
buy_info_arr = []

# 判断此次交易得分（是否为好交易）
buy_evaluate_arr = []
buy_evaluate1_arr = []
buy_evaluate2_arr = []
buy_evaluate3_arr = []
buy_evaluate5_arr = []
buy_evaluate10_arr = []
evaluate_good_arr = []
evaluate_bad_arr = []
buy_evaluate_good_arr = []
buy_evaluate_bad_arr = []
sell_evaluate_good_arr = []
sell_evaluate_bad_arr = []

# 每时刻的资产数据
asset_own_arr = []
stock_num_arr = []
asset_share_arr = []
asset_all_arr = []
# 买操作次数
buy_num = 0
# 卖操作次数
sell_num = 0
operation_num = 0
good_buy_num = 0
good_sell_num = 0
# 上次进行买或卖的index
last_buy_i = 0
last_sell_i = 0
last_buy_or_sell_i = 0

# 测试用的（正式不用）
data_frame = None


# 根据获取的策略初始化数据
def judge_init(code):
    # 股票数据初始化
    global code_num
    global now
    global data_all
    global data_close
    global data_open
    global data_highest
    global data_lowest
    global data_trend
    global data_MA5
    global data_MA10
    global data_MA20
    global data_MA30
    global data_increase
    global data_time
    code_num = code
    data_all = get_data(code)
    data_open = data_all['开盘']
    data_close = data_all['收盘']
    data_highest = data_all['最高']
    data_lowest = data_all['最低']
    data_time = data_all['日期']
    data_MA5 = data_close.rolling(5).mean().round(2).bfill()
    data_MA10 = data_close.rolling(10).mean().round(2).bfill()
    data_MA20 = data_close.rolling(20).mean().round(2).bfill()
    data_MA30 = data_close.rolling(30).mean().round(2).bfill()
    data_increase = ((data_all['收盘'] - data_all['开盘']) / data_all['开盘']).round(4)
    # 将数据保存到csv
    s_close = pd.Series(data_close, name='close')
    s_open = pd.Series(data_open, name='open')
    s_highest = pd.Series(data_highest, name='highest')
    s_lowest = pd.Series(data_lowest, name='lowest')
    # s_trend = pd.Series(data_trend, name='trend')
    global data_frame
    data_frame = pd.DataFrame({'open': s_open, 'close': s_close, 'lowest': s_lowest, 'highest': s_highest})
    data_frame.to_csv('data_frame.csv')

    # 其他数据格式化
    global asset_own
    global asset_share
    asset_own = 100000
    asset_share = 0


def get_data(code):
    return pd.read_csv('web/stockDetail/' + code + '/data.csv')


def get_strategy(strategy_name):
    global strategy
    strategy_file = open('web/json/init_info.json', 'r', encoding='utf-8')
    strategy = json.load(strategy_file)
    return strategy["allStrategy"][strategy_name]


# 返回处理open数据后的logic_str
# open(2) 两天前的open
def get_open_str(logic_str):
    global now
    logic_str = logic_str.replace('{open}', '(' + str(data_open[now]) + ')')
    r = re.compile(r'{open\((.*?)\)}')
    arr = re.findall(r, logic_str)
    # item : 括号里的内容 arr: 数组（可能有多个{open()}）
    for item in arr:
        target_i = now
        if item != "":
            target_i = now - int(item) if (now - int(item)) >= 0 else 0
        logic_str = r.sub('(' + str(data_open[target_i]) + ')', logic_str, count=1)
    return logic_str


def get_close_str(logic_str):
    global now
    logic_str = logic_str.replace('{close}', '(' + str(data_close[now]) + ')')
    r = re.compile(r'{close\((.*?)\)}')
    arr = re.findall(r, logic_str)
    # item : 括号里的内容 arr: 数组（可能有多个{open()}）
    for item in arr:
        target_i = now
        if item != "":
            target_i = now - int(item) if (now - int(item)) >= 0 else 0
        logic_str = r.sub('(' + str(data_close[target_i]) + ')', logic_str, count=1)
    return logic_str


def get_lowest_str(logic_str):
    global now
    logic_str = logic_str.replace('{lowest}', '(' + str(data_lowest[now]) + ')')
    r = re.compile(r'{lowest\((.*?)\)}')
    arr = re.findall(r, logic_str)
    # item : 括号里的内容 arr: 数组（可能有多个{open()}）
    for item in arr:
        target_i = now
        if item != "":
            target_i = now - int(item) if (now - int(item)) >= 0 else 0
        logic_str = r.sub('(' + str(data_lowest[target_i]) + ')', logic_str, count=1)
    return logic_str


def get_highest_str(logic_str):
    global now
    logic_str = logic_str.replace('{highest}', '(' + str(data_highest[now]) + ')')
    r = re.compile(r'{highest\((.*?)\)}')
    arr = re.findall(r, logic_str)
    # item : 括号里的内容 arr: 数组（可能有多个{open()}）
    for item in arr:
        target_i = now
        if item != "":
            target_i = now - int(item) if (now - int(item)) >= 0 else 0
        logic_str = r.sub('(' + str(data_highest[target_i]) + ')', logic_str, count=1)
    return logic_str


# 计算趋势是否
def count_trend(days):
    before = (now - days) if (now - days) >= 0 else 0
    return (data_close[now] - data_close[before]) / data_close[before]


# trend(n)
# 获取趋势(当天收盘价-n天前的收盘价)/n天前收盘价
def get_trend_str(logic_str):
    r = re.compile(r'{trend\((.*?)\)}')
    arr = re.findall(r, logic_str)
    # item: 括号内的天数
    for item in arr:
        # 默认1天前
        target_i = 1
        if item != "":
            target_i = int(item)
        logic_str = r.sub('(' + str(count_trend(target_i)) + ')', logic_str, count=1)
    return logic_str


# 距离上次买入后的最大值
def get_after_buy_max_str(logic_str):
    r = re.compile(r'{max_after_buy.*?}')
    global last_buy_i
    global now
    get_max = pd.Series(data_close).loc[last_buy_i:now].max()
    logic_str = r.sub('(' + str(get_max) + ')', logic_str)
    return logic_str


# def get_after_buy_max_str(logic_str,day):
#     r = re.compile(r'{max_after_buy.*?}')
#     global last_buy_i
#     global now
#
#     get_max = pd.Series(data_close).loc[last_buy_i:day + 1].max()
#     logic_str = r.sub('(' + str(get_max) + ')', logic_str)
#     return logic_str


# MA MA(5) 当天的5日均线
def get_MA_str(logic_str):
    global data_close
    r = re.compile(r'{MA\((.*?)\)}')
    arr = re.findall(r, logic_str)
    # item: days: MA(days)
    for item in arr:
        before = (now - int(item)) if (now - int(item)) >= 0 else 0
        data_section = data_close[before:now + 1]
        d = sum(data_section) / (now - before + 1)
        logic_str = r.sub('(' + str(d) + ')', logic_str, count=1)
    return logic_str


def get_MA5_str(logic_str):
    global data_MA5
    # r_com = re.compile(r'{MA5()}')
    logic_str = logic_str.replace('{MA5}', '(' + str(data_MA5[now]) + ')')
    logic_str = logic_str.replace('{MA5()}', '(' + str(data_MA5[now]) + ')')
    r = re.compile(r'{MA5\((.*?)\)}')
    arr = re.findall(r, logic_str)
    # item : days
    for item in arr:
        target = (now - int(item)) if (now - int(item)) > 0 else 0
        logic_str = r.sub('(' + str(data_MA5[target]) + ')', logic_str, count=1)
    return logic_str


#
def get_increase_str(logic_str):
    global data_increase
    logic_str = logic_str.replace('{increase}', '(' + str(data_increase[now]) + ')')
    logic_str = logic_str.replace('{increase()}', '(' + str(data_increase[now]) + ')')
    r = re.compile(r'{increase\((.*?)\)}')
    arr = re.findall(r, logic_str)
    for item in arr:
        target = (now - int(item)) if (now - int(item)) > 0 else 0
        logic_str = r.sub('(' + str(data_increase[target]) + ')', logic_str, count=1)
    return logic_str


# ----------------------------------
# 分界线 ↑:获取工具  ↓：逻辑相关
# ----------------------------------


# 先替换所有变量，再计算
# 返回值为bool
# "{open}*2>{close}*2", "{trend(5)>0.05}"
def logic_judge(logic_str):
    logic_str = get_open_str(logic_str)
    logic_str = get_close_str(logic_str)
    logic_str = get_lowest_str(logic_str)
    logic_str = get_highest_str(logic_str)
    logic_str = get_trend_str(logic_str)
    logic_str = get_after_buy_max_str(logic_str)
    logic_str = get_MA_str(logic_str)
    logic_str = get_MA5_str(logic_str)
    logic_str = get_increase_str(logic_str)
    # print(logic_str)

    logic_return = eval(logic_str)
    return logic_return


# 获取未来几天的趋势，用于判断交易是否为好
# i: 未来几天 10%
def get_future_trend_score(i):
    if (now + i) >= (len(data_close)):
        return 0
    target_i = now + i
    trend_per = (data_close[target_i] - data_close[now]) / data_close[now] * i * 100
    return trend_per


# 第i天买入
def buy_func(i):
    global data_close
    global asset_share
    global asset_own
    global stock_num
    global last_buy_i
    global last_buy_or_sell_i
    last_buy_i = i
    last_buy_or_sell_i = i
    stock_price = data_close[i]
    stock_num = math.floor(asset_own / stock_price)
    asset_share = stock_num * stock_price
    asset_own = asset_own % stock_price
    # 评价此次购买交易
    # 抄底最好，所以根据1、2、3、5、10日涨幅
    # 如果为跌，则不是谷底，为不好，根据情况打分
    # 如果为涨，则为谷底，为好，根据情况打分
    global buy_evaluate_arr
    global buy_evaluate1_arr
    global buy_evaluate2_arr
    global buy_evaluate3_arr
    global buy_evaluate5_arr
    global buy_evaluate10_arr
    global evaluate_good_arr
    global buy_evaluate_good_arr
    global evaluate_bad_arr
    global buy_evaluate_bad_arr
    global good_buy_num
    score1 = get_future_trend_score(1)
    score2 = get_future_trend_score(2)
    score3 = get_future_trend_score(3)
    score5 = get_future_trend_score(5)
    score10 = get_future_trend_score(10)
    # 结果为-10 - 10
    score_return = (score1 + score2 + score3 + score5 + score10) / 21
    buy_evaluate_arr[i] = score_return
    buy_evaluate1_arr[i] = score1
    buy_evaluate2_arr[i] = score2
    buy_evaluate3_arr[i] = score3
    buy_evaluate5_arr[i] = score5
    buy_evaluate10_arr[i] = score10
    if score_return > 0:
        evaluate_good_arr.append(data_time[i])
        buy_evaluate_good_arr.append(data_time[i])
        good_buy_num = good_buy_num + 1
    else:
        evaluate_bad_arr.append(data_time[i])
        buy_evaluate_bad_arr.append(data_time[i])


# 第i天卖
def sell_func(i):
    global data_close
    global asset_share
    global asset_own
    global stock_num
    global last_sell_i
    global last_buy_or_sell_i
    global good_sell_num
    last_sell_i = i
    last_buy_or_sell_i = i
    stock_price = data_close[i]
    asset_own = asset_own + (stock_price * stock_num)
    stock_num = 0
    asset_share = 0
    # 评价此次卖出交易
    # 顶峰最好，所以根据1、2、3、5、10日涨幅
    # 如果为跌，则是顶峰，为好，根据情况打分
    # 如果为涨，则不为顶峰，为不好，根据情况打分
    global buy_evaluate_arr
    global buy_evaluate1_arr
    global buy_evaluate2_arr
    global buy_evaluate3_arr
    global buy_evaluate5_arr
    global buy_evaluate10_arr
    global evaluate_good_arr
    global evaluate_bad_arr
    global sell_evaluate_good_arr
    global sell_evaluate_bad_arr
    score1 = get_future_trend_score(1)
    score2 = get_future_trend_score(2)
    score3 = get_future_trend_score(3)
    score5 = get_future_trend_score(5)
    score10 = get_future_trend_score(10)
    # 结果为-10 - 10
    score_return = -(score1 + score2 + score3 + score5 + score10) / 21
    buy_evaluate_arr[i] = score_return
    buy_evaluate1_arr[i] = score1
    buy_evaluate2_arr[i] = score2
    buy_evaluate3_arr[i] = score3
    buy_evaluate5_arr[i] = score5
    buy_evaluate10_arr[i] = score10
    if score_return > 0:
        evaluate_good_arr.append(data_time[i])
        sell_evaluate_good_arr.append(data_time[i])
        good_sell_num = good_sell_num + 1
    else:
        evaluate_bad_arr.append(data_time[i])
        sell_evaluate_bad_arr.append(data_time[i])


# bool_buy :
# name: 策略名字
# bool_buy: 买（true） 卖（false）
def mark_point_push(name, bool_buy, i):
    global mark_point_arr
    global buy_info_arr
    mark_json = {}
    coord = [data_all['日期'].loc[i], data_close[i]]
    item_style = {}
    if bool_buy == 1:
        item_style["color"] = 'rgba(235,84,84,0.7)'
        item_style["borderColor"] = 'rgba(100,100,100,0.3)'
    else:
        item_style["color"] = 'rgba(71,178,98,0.7)'
        item_style["borderColor"] = 'rgba(100,100,100,0.3)'
    mark_json["name"] = name
    mark_json["coord"] = coord
    mark_json["value"] = data_close[i]
    mark_json["itemStyle"] = item_style
    mark_point_arr.append(mark_json)


def init_result(i):
    global asset_all
    asset_all = asset_own + asset_share
    asset_own_arr.append(asset_own)
    stock_num_arr.append(stock_num)
    asset_share_arr.append(asset_share)
    asset_all_arr.append(asset_all)


@eel.expose
def change_logic_content(is_buy, strategy_name, item):
    print(is_buy)
    print(strategy_name)
    print(item)
    print(item["name"])
    logic_type = ""
    if is_buy:
        logic_type = "buyLogic"
    else:
        logic_type = "sellLogic"
    info_file = open('web/json/init_info.json', 'r', encoding='utf-8')
    info_data = json.load(info_file)
    print(info_data["allStrategy"][strategy_name][logic_type])
    logic_arr = info_data["allStrategy"][strategy_name][logic_type]
    for info_item in logic_arr:
        if info_item["name"] == item["name"]:
            info_item["value"] = item["value"]
    info_data["allStrategy"][strategy_name][logic_type] = logic_arr
    print("info_data:")
    print(info_data)
    info_file.close()
    info_file2 = open('web/json/init_info.json', 'w', encoding='utf-8')
    json.dump(info_data, info_file2, ensure_ascii=False)
    print("更改完成")


# main 判断入口
@eel.expose()
def judge(code, strategy_name):
    global last_buy_i
    global last_sell_i
    global last_buy_or_sell_i
    last_buy_i = 0
    last_sell_i = 0
    last_buy_or_sell_i = 0

    global status_buy
    global now
    global data_all
    global data_close
    global data_open
    global data_highest
    global data_lowest
    global data_trend
    global strategy
    status_buy = True
    data = get_data(code)
    strategy = get_strategy(strategy_name)
    logic_buy_arr = strategy["buyLogic"]
    logic_sell_arr = strategy["sellLogic"]
    judge_init(code)

    # 买卖记录arr
    global mark_point_arr
    global buy_info_arr
    global asset_all_arr
    global asset_share_arr
    global asset_own_arr
    global buy_arr
    global sell_arr
    global stock_num_arr
    global buy_num
    global sell_num
    global operation_num

    global buy_evaluate_arr
    global buy_evaluate_arr
    global buy_evaluate1_arr
    global buy_evaluate2_arr
    global buy_evaluate3_arr
    global buy_evaluate5_arr
    global buy_evaluate10_arr
    global evaluate_good_arr
    global evaluate_bad_arr
    global buy_evaluate_good_arr
    global buy_evaluate_bad_arr
    global sell_evaluate_good_arr
    global sell_evaluate_bad_arr
    global good_buy_num
    global good_sell_num
    buy_evaluate_arr = [""] * data.shape[0]
    buy_evaluate1_arr = [""] * data.shape[0]
    buy_evaluate2_arr = [""] * data.shape[0]
    buy_evaluate3_arr = [""] * data.shape[0]
    buy_evaluate5_arr = [""] * data.shape[0]
    buy_evaluate10_arr = [""] * data.shape[0]
    evaluate_good_arr = []
    evaluate_bad_arr = []
    buy_evaluate_good_arr = []
    buy_evaluate_bad_arr = []
    sell_evaluate_good_arr = []
    sell_evaluate_bad_arr = []
    good_buy_num = 0
    good_sell_num = 0

    mark_point_arr = []
    buy_info_arr = []
    asset_all_arr = []
    asset_share_arr = []
    asset_own_arr = []
    buy_arr = []
    sell_arr = []
    stock_num_arr = []
    buy_evaluate_arr = []
    buy_num = 0
    sell_num = 0

    buy_arr = [""] * data.shape[0]
    sell_arr = [""] * data.shape[0]
    buy_evaluate_arr = [""] * data.shape[0]
    for i in data.index:
        now = i
        # 根据一天前的涨幅，判断这次买或者卖是否为好操作
        trend_1d = get_trend_str("{trend(1)}")
        status_buy_or_sell = ""
        last_logic_name = ""
        # 如果可买，只判断logic_buy
        if status_buy:
            # item: {"name":"","value":""}
            for logic_buy_arr_item in logic_buy_arr:
                logic_return = bool(logic_judge(logic_buy_arr_item["value"]))
                # 符合买的逻辑
                if logic_return:
                    status_buy = False
                    buy_arr[i] = (logic_buy_arr_item["name"])
                    mark_point_push(logic_buy_arr_item["name"], 1, i)
                    buy_func(i)
                    status_buy_or_sell = "buy"
                    last_logic_name = logic_buy_arr_item["name"]
                    buy_num += 1
                    break

        # 如果状态为 可卖，只判断logic_sell
        else:
            logic_return = True
            # item: {"name":"","value":""}
            for logic_sell_arr_item in logic_sell_arr:
                logic_return = bool(logic_judge(logic_sell_arr_item["value"]))
                # 符合卖的逻辑
                if logic_return:
                    status_buy = True
                    sell_arr[i] = (logic_sell_arr_item["name"])
                    mark_point_push(logic_sell_arr_item["name"], -1, i)
                    sell_func(i)
                    status_buy_or_sell = "sell"
                    last_logic_name = logic_sell_arr_item["name"]
                    sell_num += 1
                    break
        buy_info_json = {}
        buy_info_json["index"] = i
        buy_info_json["operation"] = status_buy_or_sell
        buy_info_json["LogicName"] = last_logic_name
        buy_info_arr.append(buy_info_json)
        init_result(i)

    judge_result_json = {}
    judge_result_json["time"] = data_time.values.tolist()
    judge_result_json["increase"] = data_increase.values.tolist()
    judge_result_json["asset_own"] = asset_own_arr
    judge_result_json["asset_share"] = asset_share_arr
    judge_result_json["stock_num"] = stock_num_arr
    judge_result_json["asset_all"] = asset_all_arr
    judge_result_json["mark_point"] = mark_point_arr
    judge_result_json["buy_info"] = buy_info_arr
    judge_result_json["buy_evaluate"] = buy_evaluate_arr
    judge_result_json["buy_evaluate1"] = buy_evaluate1_arr
    judge_result_json["buy_evaluate2"] = buy_evaluate2_arr
    judge_result_json["buy_evaluate3"] = buy_evaluate3_arr
    judge_result_json["buy_evaluate5"] = buy_evaluate5_arr
    judge_result_json["buy_evaluate10"] = buy_evaluate10_arr
    judge_result_json["evaluate_good"] = evaluate_good_arr  # 所有好的操作
    judge_result_json["evaluate_bad"] = evaluate_bad_arr
    judge_result_json["buy_evaluate_good"] = buy_evaluate_good_arr  # 所有好的买操作
    judge_result_json["buy_evaluate_bad"] = buy_evaluate_bad_arr
    judge_result_json["sell_evaluate_good"] = sell_evaluate_good_arr
    judge_result_json["sell_evaluate_bad"] = sell_evaluate_bad_arr

    # print("judge_result_json")
    # print(judge_result_json)
    judge_result_file = open('web/stockDetail/' + code + '/judge_result.json', mode='w', encoding='utf-8')
    # ensure_ascii=False 代表中文不转义
    json.dump(judge_result_json, judge_result_file, ensure_ascii=False)
    judge_result_file.close()

    judge_sketch = {}
    judge_sketch["assetOwn"] = asset_own_arr[-1]
    judge_sketch["assetShare"] = asset_share_arr[-1]
    judge_sketch["assetAll"] = asset_all_arr[-1]
    judge_sketch["buyNum"] = buy_num
    judge_sketch["sellNum"] = sell_num
    judge_sketch["goodBuyNum"] = good_buy_num
    judge_sketch["goodSellNum"] = good_sell_num
    judge_sketch_file = open('web/stockDetail/' + code + "/judge_sketch.json", 'w', encoding='utf-8')
    json.dump(judge_sketch, judge_sketch_file, ensure_ascii=False)

    global judge_item_json
    judge_item_json = {}
    judge_item_json["asset_end"] = asset_all_arr[-1]
    judge_item_json["asset_beg"] = 100000
    judge_item_json["rate"] = (asset_all_arr[-1] - 100000) / 100000 * 100
    judge_item_json["buyNum"] = buy_num
    judge_item_json["sellNum"] = sell_num
    judge_item_json["goodBuyNum"] = good_buy_num
    judge_item_json["goodSellNum"] = good_sell_num

    # 表示完成（因为时间比较长，所有需要异步进行）
    return True


@eel.expose
def get_all_code_enum():
    info_file = open('web/json/init_info.json', 'r', encoding='utf-8')
    info_json = json.load(info_file)
    stock_enum = info_json["stockEnum"]
    return stock_enum


# 暂存judge选择的股票结果（全局）
judge_item_json = {}


@eel.expose
def judge_all(all_stock_list, selected_stock_list, strategy_name):
    global judge_item_json
    all_stock_str = str(all_stock_list).replace("\'", "\"")
    selected_stock_str = str(selected_stock_list).replace("\'", "\"")
    print(all_stock_str)
    print(selected_stock_str)
    all_stock_json = json.loads(str(all_stock_str))
    selected_stock_json = json.loads(str(selected_stock_str))
    all_stock_df = pd.json_normalize(all_stock_json)
    selected_stock_df = pd.json_normalize(selected_stock_json)
    all_stock_df['asset_beg'] = ''
    all_stock_df['asset_end'] = ''
    all_stock_df['rate'] = ''
    all_stock_df['buyNum'] = ''
    all_stock_df['sellNum'] = ''
    all_stock_df['goodBuyNum'] = ''
    all_stock_df['goodSellNum'] = ''
    print("all_stock_df")
    print(all_stock_df)
    print("selected_stock_df")
    print(selected_stock_df)
    all_stock_df.set_index("code", inplace=True, drop=False)
    # all_stock_df = all_stock_df.loc[:,['code','name','price','beg','end','rate']]

    # 统计股票数量
    all_stock_num = 0
    # 统计盈利股票个数
    profit_num = 0
    # 统计亏损股票个数
    loss_num = 0
    # 最高盈利率
    profit_max = 0
    # 最高亏损率
    loss_max = 0
    # 总盈利率
    all_rate = 0
    all_profit = 0
    all_loss = 0
    profit_arr = []
    loss_arr = []
    judge_analysis_json = {}
    for index, item in selected_stock_df.iterrows():
        item_code = item["code"]
        print(item_code)
        judge_return = judge(item_code, strategy_name)
        print(judge_return)
        all_stock_df.loc[item_code, "asset_beg"] = judge_item_json["asset_beg"]
        all_stock_df.loc[item_code, "asset_end"] = judge_item_json["asset_end"]
        all_stock_df.loc[item_code, "rate"] = judge_item_json["rate"]
        all_stock_df.loc[item_code, "buyNum"] = judge_item_json["buyNum"]
        all_stock_df.loc[item_code, "sellNum"] = judge_item_json["sellNum"]
        all_stock_df.loc[item_code, "goodBuyNum"] = judge_item_json["goodBuyNum"]
        all_stock_df.loc[item_code, "goodSellNum"] = judge_item_json["goodSellNum"]
        rate = judge_item_json['rate']
        # 如果为盈利
        if rate > 0:
            profit_num = profit_num + 1
            profit_max = rate if rate > profit_max else profit_max
            profit_arr.append(item_code)
            all_profit = all_profit + rate
        # 如果为亏损
        else:
            loss_num = loss_num + 1
            loss_max = rate if rate < loss_max else loss_max
            loss_arr.append(item_code)
            all_loss = all_loss + rate
        all_stock_num = all_stock_num + 1
        all_rate = all_rate + rate
    judge_analysis_json["stockNum"] = all_stock_num
    judge_analysis_json["profitNum"] = profit_num
    judge_analysis_json["lossNum"] = loss_num
    judge_analysis_json["profitMax"] = profit_max
    judge_analysis_json["lossMax"] = loss_max
    judge_analysis_json["meanProfit"] = all_profit / profit_num if profit_num != 0 else 0
    judge_analysis_json["meanLoss"] = all_loss / loss_num if loss_num != 0 else 0
    judge_analysis_json["allRate"] = all_rate
    judge_analysis_json["meanRate"] = all_rate / all_stock_num
    judge_analysis_json["profitArr"] = profit_arr
    judge_analysis_json["lossArr"] = loss_arr
    judge_analysis_file = open('web/stockDetail/judge_analysis.json', 'w', encoding='utf-8')
    json.dump(judge_analysis_json, judge_analysis_file, ensure_ascii=False, indent=2)
    judge_analysis_file.close()
    print("all_stock_df:")
    print(all_stock_df)
    # all_stock_df.to_csv('web/stockDetail/all_stock_judge_result.txt', encoding='utf-8', header=False, index=True)
    all_stock_df.to_json('web/stockDetail/all_stock_judge_result.json', index=True, orient="records")
    print("判断成功")
    return True


def get_table_only_code():
    info_file = open('web/json/init_info.json', 'r', encoding='utf-8')
    info_json = json.load(info_file)
    stock_enum = info_json["stockEnum"]
    stock_enum_df = pd.DataFrame({"code": stock_enum})
    data_json_t = stock_enum_df.to_json(orient='table')
    data_json = json.loads(data_json_t)["data"]
    return data_json


@eel.expose
def select_target_judge(code, strategy_name):
    print("select target judge")
    set_selected_file = open('web/global/stepSelected.json', 'w', encoding='utf-8')
    step_json = {"code": code, "strategyName": strategy_name}
    json.dump(step_json, set_selected_file, ensure_ascii=False, indent=2)
    set_selected_file.close()


@eel.expose
def clear_step_selected_file():
    file = open('web/global/stepSelected.json', 'w', encoding='utf-8')
    empty_json = {}
    json.dump(empty_json, file, ensure_ascii=False, indent=2)
    file.close()


import akshare as ak


###########
# 股票相关
###########
@eel.expose
def get_stock_list():
    init_info_file = open('web/json/init_info.json', 'r', encoding='utf-8')
    init_info_json = json.load(init_info_file)
    stock_enum = init_info_json['stockEnum']
    print(stock_enum)
    df = ak.stock_zh_a_spot_em()
    print(df.columns)
    df.rename(columns={'代码': 'code', '名称': 'name', '最新价': 'price'}, inplace=True)
    print(df.columns)
    df.set_index('code', inplace=True, drop=False)
    df_no = df.loc[:, ['code', 'name', 'price']]
    df_yes = df_no.loc[stock_enum, :]
    df_no.drop(index=stock_enum, inplace=True)
    df_yes.to_json('web/stockDetail/stock_yes.json', index=True, orient='records')
    df_no.to_json('web/stockDetail/stock_no.json', index=True, orient="records")
    return True



@eel.expose
def getLogicChineseContent(logic_str):
    print("getLogicChineseContent---logic_str:"+logic_str)
    r = re.compile(r'\s*and\s*')
    logic_str = r.sub('   且   ', logic_str)
    # logic_str = logic_str.replace('and', "  且  ")

    r = re.compile(r'\s*>\s*')
    logic_str = r.sub(' > ', logic_str)
    # logic_str = logic_str.replace('and', "  且  ")

    # 开盘价
    logic_str = logic_str.replace('{open}', '当天开盘价')
    logic_str = logic_str.replace('{open()}', '当天开盘价')
    logic_str = logic_str.replace('{open(0)}', '当天开盘价')
    r = re.compile(r'{open\((.*?)\)}')
    arr = re.findall(r, logic_str)
    # item : 括号里的内容 arr: 数组（可能有多个{open()}）
    for item in arr:
        logic_str = r.sub(item + '天前开盘价', logic_str, count=1)

    # 收盘价
    logic_str = logic_str.replace('{close}', '当天收盘价')
    logic_str = logic_str.replace('{close()}', '当天收盘价')
    logic_str = logic_str.replace('{close(0)}', '当天收盘价')
    r = re.compile(r'{close\((.*?)\)}')
    arr = re.findall(r, logic_str)
    # item : 括号里的内容 arr: 数组（可能有多个{open()}）
    for item in arr:
        logic_str = r.sub(item + '天前收盘价', logic_str, count=1)

    # 5日均线
    logic_str = logic_str.replace('{MA5}', '当天5日均线')
    logic_str = logic_str.replace('{MA5()}', '当天5日均线')
    logic_str = logic_str.replace('{MA5(0)}', '当天5日均线')
    r = re.compile(r'{MA5\((.*?)\)}')
    arr = re.findall(r, logic_str)
    # item : 括号里的内容 arr: 数组（可能有多个{open()}）
    for item in arr:
        logic_str = r.sub(item + '天前5日均线', logic_str, count=1)

    # 10日均线
    logic_str = logic_str.replace('{MA10}', '当天10日均线')
    logic_str = logic_str.replace('{MA10()}', '当天10日均线')
    logic_str = logic_str.replace('{MA10(0)}', '当天10日均线')
    r = re.compile(r'{MA10\((.*?)\)}')
    arr = re.findall(r, logic_str)
    # item : 括号里的内容 arr: 数组（可能有多个{open()}）
    for item in arr:
        logic_str = r.sub(item + '天前10日均线', logic_str, count=1)

    # 20日均线
    logic_str = logic_str.replace('{MA20}', '当天20日均线')
    logic_str = logic_str.replace('{MA20()}', '当天20日均线')
    logic_str = logic_str.replace('{MA20(0)}', '当天20日均线')
    r = re.compile(r'{MA20\((.*?)\)}')
    arr = re.findall(r, logic_str)
    # item : 括号里的内容 arr: 数组（可能有多个{open()}）
    for item in arr:
        logic_str = r.sub(item + '天前20日均线', logic_str, count=1)

    # 30日均线
    logic_str = logic_str.replace('{MA30}', '当天30日均线')
    logic_str = logic_str.replace('{MA30()}', '当天30日均线')
    logic_str = logic_str.replace('{MA30(0)}', '当天30日均线')
    r = re.compile(r'{MA30\((.*?)\)}')
    arr = re.findall(r, logic_str)
    # item : 括号里的内容 arr: 数组（可能有多个{open()}）
    for item in arr:
        logic_str = r.sub(item + '天前30日均线', logic_str, count=1)

    # 前几天趋势
    logic_str = logic_str.replace('{trend}', '当天趋势')
    logic_str = logic_str.replace('{trend()}', '当天趋势')
    logic_str = logic_str.replace('{trend(0)}', '当天趋势')
    r = re.compile(r'{trend\((.*?)\)}')
    arr = re.findall(r, logic_str)
    # item : 括号里的内容 arr: 数组（可能有多个{open()}）
    for item in arr:
        logic_str = r.sub('前' + item + '天趋势', logic_str, count=1)
    print(logic_str)
    return_json = {}
    return_json["data"] = logic_str
    # return return_json
    return logic_str

# print("judge")
# code = "688338"
# strategy = "strategy1"
# judge(code,strategy)


web_app_options = {
    # 指定浏览器，默认也是谷歌浏览器 #or “chrome”
    'mode': 'chrome-app',
    # 指定端口，默认也是这个端口
    'port': 9999,
    # –kiosk 是chrome的全屏参数
    'chromeFlags': ["–kiosk"]
}

print("初始化完成！")
# , '--browser-startup-dialog'
eel.start('step.html', mode='edge', port=9999, cmdline_args=['--start-fullscreen'],
          suppress_error=True)

input('Press Enter to exit...')
